﻿using UnityEngine;
using System.Collections;
using System;
using System.IO;
using ProtoBuf;

namespace TCG
{
	/// <summary>
	/// 加载游戏资源，控制并发性、加载优先级等（待实现）。所有的加载请求最终汇集到这里。
	/// </summary>

	public class GameAssetsLoader : MonoBehaviour 
	{
        /// <summary>
        /// 初始化.
        /// </summary>

		public void Initialize ()
		{

		}

        /// <summary>
        /// 加载指定路径处的assetBundles.
        /// </summary>

        public void LoadAssetBundle (AssetRequest request, Action<AssetRequest, AssetBundle> callback)
        {
			Debug.Log ("开始加载资源：" + request.assetUrl);

			StartCoroutine (_LoadAssetBundle (request, callback));
        }

        /// <summary>
        /// 反序列化处指定路径处的Protobuf流为指定类型T.
        /// </summary>

        public void LoadProtobufStream<T> (AssetRequest request, Action<AssetRequest, T> callback) where T : class
        {
			Debug.Log ("开始加载资源：" + request.assetUrl);

            try
            {
                FileStream stream = new FileStream (request.assetUrl, FileMode.Open);
                T data = Serializer.Deserialize<T> (stream);
                stream.Close ();
                callback (request, data);
            }
            catch (Exception e)
            {
                request.error = e.Message;
                callback (request, null);
            }
        }

		IEnumerator _LoadAssetBundle (AssetRequest request, Action<AssetRequest, AssetBundle> callback)
		{
			WWW www = new WWW ("file://" + request.assetUrl);
			yield return www;

            if (!string.IsNullOrEmpty (www.error))
			{
				request.error = www.error;
				callback (request, null);
			}
			else
			{
				callback (request, www.assetBundle);
			}
		}
	}
}
